package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    //购物车
    @Autowired
    private ShoppingCartService shoppingCartService;

    //user地址表
    @Autowired
    private AddressBookService addressBookService;

    //user数据表
    @Autowired
    private UserService userService;

    //订单明细
    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 下单用户
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        //判断购物车是否有数据，如果没有就抛异常
        if(shoppingCartList==null||shoppingCartList.size()==0){
            throw new CustomException("购物车为空,不能下单");
        }
        //用户数据
        User user = userService.getById(userId);
        //查询地址表,要用户的地址信息
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getIsDefault,1);
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,userId);
        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);
        //判断地址信息是否有数据，如果没有就抛异常
        if(addressBook==null){
            throw new CustomException("地址为空,不能下单");
        }



        //生成id订单号
        long ordersId = IdWorker.getId();

        //设置原子性的总金额计算
        AtomicInteger amount = new AtomicInteger(0);

        //遍历购物车该用户所有的商品，封装成明细集合，另外计算出总金额是多少
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item)->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setImage(item.getImage());
            orderDetail.setName(item.getName());
            orderDetail.setOrderId(ordersId);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //组装Orders对象的数据
        orders.setId(ordersId);
        orders.setNumber(String.valueOf(ordersId)); //订单编号
        orders.setStatus(2);//状态
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(BigDecimal.valueOf(amount.get()));
        orders.setUserName(user.getName());
        orders.setPhone(user.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //向订单表插入数据,一条数据
        this.save(orders);

        orders.setPayMethod(1);
        //向订单明细表插入,多条数据与
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
    }

    /**
     * 用户再来一单
     * @param orders
     */
    @Transactional
    @Override
    public void again(Orders orders) {
        //获取订单号
        String number = orders.getNumber();
        //查询订单详情表中的数据
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(StringUtils.hasLength(number),OrderDetail::getOrderId,number);

        //获取订单号下所有菜品
        List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);

        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item, shoppingCart);
            //设置用户id
            shoppingCart.setUserId(BaseContext.getCurrentId());
            return shoppingCart;
        }).collect(Collectors.toList());

        //批量添加到购物车中
        shoppingCartService.saveBatch(shoppingCartList);

    }
}
